import os
import sys
import subprocess
from datetime import timedelta

def get_duration(file_path):
    """Get the duration of an audio file in seconds."""
    result = subprocess.run(
        ['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', file_path],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT
    )
    return int(float(result.stdout))

def combine_aac_files(folder_path, max_duration=3 * 60 * 60):
    """Combine AAC files in the given folder, keeping each combined file under max_duration."""
    os.chdir(folder_path)
    output_files = []
    current_files = []
    current_duration = 0
    file_count = 1

    for file in sorted(os.listdir()):
        if not file.endswith('.aac') or file.startswith('combined_'):
            continue

        file_duration = get_duration(file)

        if current_duration + file_duration > max_duration:
            # Combine current files
            output_file = f"combined_{file_count}.aac"
            combine_command = ['ffmpeg', '-i', f"concat:{'|'.join(current_files)}", '-c', 'copy', output_file]
            subprocess.run(combine_command, check=True)
            print(f"Created {output_file}")
            output_files.append(output_file)

            # Reset for next batch
            current_files = []
            current_duration = 0
            file_count += 1

        current_files.append(file)
        current_duration += file_duration
        print(f"Added {file} to list for combined_{file_count}.aac (Current duration: {timedelta(seconds=current_duration)})")

    # Combine any remaining files
    if current_files:
        output_file = f"combined_{file_count}.aac"
        combine_command = ['ffmpeg', '-i', f"concat:{'|'.join(current_files)}", '-c', 'copy', output_file]
        subprocess.run(combine_command, check=True)
        print(f"Created {output_file}")
        output_files.append(output_file)

    print(f"Finished combining files. Created {len(output_files)} output file(s).")
    return output_files

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python script.py <folder_path>")
        sys.exit(1)

    folder_path = sys.argv[1]
    if not os.path.isdir(folder_path):
        print(f"Error: {folder_path} is not a valid directory.")
        sys.exit(1)

    print(f"Combining AAC files in {folder_path}...")
    combined_files = combine_aac_files(folder_path)
    print("All operations completed.")
    print("Combined files:", combined_files)
